let seed = 0;
export default class Utils {
  static isLocal() {
    return process.env.NODE_ENV !== 'production';
  }

  static guid(prefix = '') {
    let id = Date.now().toString().split('').reverse().join('') + seed++;
    return prefix ? `${prefix}_${id}` : Number(id);
  }

  static addEvent(el, event, handler) {
    if (!el) return;
    if (el.attachEvent) {
      el.attachEvent('on' + event, handler);
    } else if (el.addEventListener) {
      el.addEventListener(event, handler, false);
    } else {
      el['on' + event] = handler;
    }
  }

  static removeEvent(el, event, handler) {
    if (!el) return;
    if (el.detachEvent) {
      el.detachEvent('on' + event, handler);
    } else if (el.removeEventListener) {
      el.removeEventListener(event, handler, false);
    } else {
      el['on' + event] = null;
    }
  }

  static getDisplayName(component) {
    return component.displayName || component.name || 'Component';
  }

  // 获取图片尺寸 todo 未完成
  static getImgSize(url) {
    let img = new Image();
    img.src = url;
    const ready = ({width, height}) => {
      return {
        width,
        height,
      };
    };
    if (img.complete) {
      return ready(img);
    }
    img.onerror = () => {
      img = img.onload = img.onerror = null;
    };
    img.onload = () => {
      ready(img);
      img = img.onload = img.onerror = null;
    };
  }

  /**
   * 按 key 合并数组并去重
   * @param base
   * @param extend
   * @returns {Array.<*>}
   */
  static mergeWithKey = (base, extend) => {
    let a = [...base];
    let b = [...extend];
    a.forEach((aa, i) => {
      b.forEach(bb => {
        if (bb.key === aa.key) {
          a.splice(i, 1);
        }
      });
    });
    return a.concat(b);
  };

  static firstUpperCase = (string) => {
    return string.toLowerCase().replace(/( |^)[a-z]/g, (L) => L.toUpperCase());
  }
}
